// 匹兹堡睡眠量表逻辑处理文件
import { psqiConfig } from '../config/psqiConfig.js';

/**
 * 计算PSQI评估结果
 * @param {Object} formData - 表单数据
 * @returns {Object} 评估结果
 */
export function calculatePSQIAssessment(formData) {
  const components = {};
  let totalScore = 0;
  
  // 组件1：主观睡眠质量 (SL06)
  components.subjective_sleep_quality = {
    name: '主观睡眠质量',
    score: parseInt(formData.SL06) || 0,
    maxScore: 3
  };
  
  // 组件2：入睡时间 (SL02 + SL051)
  const sleepLatencyMinutes = parseInt(formData.SL02) || 0;
  const sleepLatencyDifficulty = parseInt(formData.SL051) || 0;
  
  let sleepLatencyScore = 0;
  // 根据入睡时间计算分数
  if (sleepLatencyMinutes <= 15) sleepLatencyScore = 0;
  else if (sleepLatencyMinutes <= 30) sleepLatencyScore = 1;
  else if (sleepLatencyMinutes <= 60) sleepLatencyScore = 2;
  else sleepLatencyScore = 3;
  
  // 与入睡困难分数相加后转换
  const combinedLatencyScore = sleepLatencyScore + sleepLatencyDifficulty;
  let finalLatencyScore = 0;
  if (combinedLatencyScore === 0) finalLatencyScore = 0;
  else if (combinedLatencyScore <= 2) finalLatencyScore = 1;
  else if (combinedLatencyScore <= 4) finalLatencyScore = 2;
  else finalLatencyScore = 3;
  
  components.sleep_latency = {
    name: '入睡时间',
    score: finalLatencyScore,
    maxScore: 3,
    details: {
      sleepLatencyMinutes,
      sleepLatencyDifficulty,
      combinedScore: combinedLatencyScore
    }
  };
  
  // 组件3：睡眠时间 (SL04)
  const sleepDuration = parseFloat(formData.SL04) || 0;
  let sleepDurationScore = 0;
  if (sleepDuration > 7) sleepDurationScore = 0;
  else if (sleepDuration > 6) sleepDurationScore = 1;
  else if (sleepDuration > 5) sleepDurationScore = 2;
  else sleepDurationScore = 3;
  
  components.sleep_duration = {
    name: '睡眠时间',
    score: sleepDurationScore,
    maxScore: 3,
    details: {
      sleepDuration: sleepDuration + '小时'
    }
  };
  
  // 组件4：睡眠效率
  const bedtime = formData.SL01; // 上床时间
  const wakeTime = formData.SL03; // 起床时间
  const actualSleep = parseFloat(formData.SL04) || 0; // 实际睡眠时间
  
  let sleepEfficiency = 0;
  if (bedtime && wakeTime && actualSleep > 0) {
    // 计算在床时间
    const bedtimeHour = parseInt(bedtime.split(':')[0]);
    const bedtimeMinute = parseInt(bedtime.split(':')[1]);
    const waketimeHour = parseInt(wakeTime.split(':')[0]);
    const waketimeMinute = parseInt(wakeTime.split(':')[1]);
    
    let bedtimeInMinutes = bedtimeHour * 60 + bedtimeMinute;
    let waketimeInMinutes = waketimeHour * 60 + waketimeMinute;
    
    // 处理跨日情况
    if (waketimeInMinutes < bedtimeInMinutes) {
      waketimeInMinutes += 24 * 60;
    }
    
    const timeInBed = (waketimeInMinutes - bedtimeInMinutes) / 60; // 转换为小时
    sleepEfficiency = timeInBed > 0 ? (actualSleep / timeInBed) * 100 : 0;
  }
  
  let sleepEfficiencyScore = 0;
  if (sleepEfficiency >= 85) sleepEfficiencyScore = 0;
  else if (sleepEfficiency >= 75) sleepEfficiencyScore = 1;
  else if (sleepEfficiency >= 65) sleepEfficiencyScore = 2;
  else sleepEfficiencyScore = 3;
  
  components.sleep_efficiency = {
    name: '睡眠效率',
    score: sleepEfficiencyScore,
    maxScore: 3,
    details: {
      efficiency: sleepEfficiency.toFixed(1) + '%',
      timeInBed: bedtime && wakeTime ? `${bedtime} - ${wakeTime}` : '未填写',
      actualSleep: actualSleep + '小时'
    }
  };
  
  // 组件5：睡眠干扰
  const disturbanceQuestions = ['SL052', 'SL053', 'SL054', 'SL055', 'SL056', 'SL057', 'SL058', 'SL059'];
  let disturbanceSum = 0;
  
  disturbanceQuestions.forEach(q => {
    disturbanceSum += parseInt(formData[q]) || 0;
  });
  
  // 添加其他问题分数
  if (formData.SL05X1) {
    disturbanceSum += parseInt(formData.SL05X1) || 0;
  }
  
  let sleepDisturbanceScore = 0;
  if (disturbanceSum === 0) sleepDisturbanceScore = 0;
  else if (disturbanceSum <= 9) sleepDisturbanceScore = 1;
  else if (disturbanceSum <= 18) sleepDisturbanceScore = 2;
  else sleepDisturbanceScore = 3;
  
  components.sleep_disturbances = {
    name: '睡眠干扰',
    score: sleepDisturbanceScore,
    maxScore: 3,
    details: {
      totalDisturbances: disturbanceSum,
      mainDisturbances: getMainDisturbances(formData)
    }
  };
  
  // 组件6：催眠药物的使用 (SL07)
  components.sleep_medication = {
    name: '催眠药物的使用',
    score: parseInt(formData.SL07) || 0,
    maxScore: 3
  };
  
  // 组件7：日间功能障碍 (SL08 + SL09)
  const daytimeSleepiness = parseInt(formData.SL08) || 0;
  const energyLack = parseInt(formData.SL09) || 0;
  
  let daytimeDysfunctionScore = 0;
  const combinedDaytimeScore = daytimeSleepiness + energyLack;
  if (combinedDaytimeScore === 0) daytimeDysfunctionScore = 0;
  else if (combinedDaytimeScore <= 2) daytimeDysfunctionScore = 1;
  else if (combinedDaytimeScore <= 4) daytimeDysfunctionScore = 2;
  else daytimeDysfunctionScore = 3;
  
  components.daytime_dysfunction = {
    name: '日间功能障碍',
    score: daytimeDysfunctionScore,
    maxScore: 3,
    details: {
      sleepiness: daytimeSleepiness,
      energyLack: energyLack,
      combinedScore: combinedDaytimeScore
    }
  };
  
  // 计算总分
  Object.values(components).forEach(component => {
    totalScore += component.score;
  });
  
  // 确定睡眠质量等级
  const qualityLevel = totalScore <= 5 ? 'good' : 'poor';
  const qualityInfo = psqiConfig.qualityLevels[qualityLevel];
  
  // 生成诊断结果
  const diagnosis = totalScore <= 5 ? '睡眠质量良好' : '睡眠质量较差';
  
  // 生成评估说明
  const explanation = totalScore <= 5 ? 
    'PSQI总分≤5分，表示睡眠质量良好，请继续保持良好的睡眠习惯。' :
    'PSQI总分>5分，表示睡眠质量较差，可能存在睡眠障碍，建议关注睡眠问题并采取相应措施。';

  return {
    totalScore,
    maxTotalScore: 21,
    components,
    qualityLevel,
    qualityInfo,
    diagnosis,
    explanation,
    sleepPartnerInfo: getSleepPartnerInfo(formData),
    recommendations: generateRecommendations(totalScore, components, formData)
  };
}

/**
 * 获取主要睡眠干扰因素
 * @param {Object} formData - 表单数据
 * @returns {Array} 主要干扰因素列表
 */
function getMainDisturbances(formData) {
  const disturbances = [];
  const disturbanceMap = {
    SL052: '夜间易醒或早醒',
    SL053: '起床上洗手间',
    SL054: '呼吸不畅',
    SL055: '鼾声或咳嗽',
    SL056: '感到太冷',
    SL057: '感到太热',
    SL058: '做恶梦',
    SL059: '疼痛不适'
  };
  
  Object.entries(disturbanceMap).forEach(([key, label]) => {
    const score = parseInt(formData[key]) || 0;
    if (score >= 2) { // 1-2次/周或更频繁
      disturbances.push({
        factor: label,
        frequency: getFrequencyLabel(score)
      });
    }
  });
  
  // 添加其他问题
  if (formData.SL05X_description && (parseInt(formData.SL05X1) || 0) >= 2) {
    disturbances.push({
      factor: formData.SL05X_description,
      frequency: getFrequencyLabel(parseInt(formData.SL05X1))
    });
  }
  
  return disturbances;
}

/**
 * 获取睡眠伙伴相关信息
 * @param {Object} formData - 表单数据
 * @returns {Object} 睡眠伙伴信息
 */
function getSleepPartnerInfo(formData) {
  const partnerStatus = parseInt(formData.SL10);
  const statusMap = {
    1: '没有睡眠伙伴',
    2: '同伴在同一房间但不同床',
    3: '同伴或室友在另一房间',
    4: '同伴在同一床上'
  };
  
  const info = {
    status: statusMap[partnerStatus] || '未填写',
    hasPartner: partnerStatus > 1,
    observations: []
  };
  
  if (partnerStatus > 1) {
    const observationMap = {
      SL101: '高声打鼾',
      SL102: '呼吸暂停',
      SL103: '腿部抽动或痉挛',
      SL104: '意识模糊'
    };
    
    Object.entries(observationMap).forEach(([key, label]) => {
      const score = parseInt(formData[key]) || 0;
      if (score > 0) {
        info.observations.push({
          behavior: label,
          frequency: getFrequencyLabel(score)
        });
      }
    });
    
    // 添加其他特殊情况
    if (formData.SL10X_description && (parseInt(formData.SL105) || 0) > 0) {
      info.observations.push({
        behavior: formData.SL10X_description,
        frequency: getFrequencyLabel(parseInt(formData.SL105))
      });
    }
  }
  
  return info;
}

/**
 * 获取频率标签
 * @param {number} score - 频率分数
 * @returns {string} 频率标签
 */
function getFrequencyLabel(score) {
  const labels = {
    0: '无',
    1: '<1次/周',
    2: '1~2次/周',
    3: '≥3次/周'
  };
  return labels[score] || '未知';
}

/**
 * 生成个性化建议
 * @param {number} totalScore - 总分
 * @param {Object} components - 各组件得分
 * @param {Object} formData - 表单数据
 * @returns {Array} 建议列表
 */
function generateRecommendations(totalScore, components, formData) {
  const recommendations = [];
  
  // 基于总分的建议
  if (totalScore <= 5) {
    recommendations.push({
      type: 'positive',
      title: '睡眠质量良好',
      content: '您的睡眠质量总体良好，请继续保持良好的睡眠习惯。'
    });
  } else {
    recommendations.push({
      type: 'warning',
      title: '睡眠质量需要改善',
      content: '您的睡眠质量存在问题，建议采取措施改善睡眠状况。'
    });
  }
  
  // 基于各组件的具体建议
  if (components.subjective_sleep_quality.score >= 2) {
    recommendations.push({
      type: 'suggestion',
      title: '改善主观睡眠感受',
      content: '建立规律的睡眠时间，创造舒适的睡眠环境，避免睡前使用电子设备。'
    });
  }
  
  if (components.sleep_latency.score >= 2) {
    recommendations.push({
      type: 'suggestion',
      title: '缩短入睡时间',
      content: '睡前1小时进行放松活动，如阅读、冥想或温水浴。避免咖啡因和剧烈运动。'
    });
  }
  
  if (components.sleep_duration.score >= 2) {
    const sleepDuration = parseFloat(formData.SL04) || 0;
    recommendations.push({
      type: 'suggestion',
      title: '增加睡眠时间',
      content: `您的睡眠时间为${sleepDuration}小时，建议成年人每晚睡眠7-9小时。尝试提前上床时间。`
    });
  }
  
  if (components.sleep_efficiency.score >= 2) {
    recommendations.push({
      type: 'suggestion',
      title: '提高睡眠效率',
      content: '避免在床上进行非睡眠活动，如看电视或使用手机。如果20分钟内无法入睡，起床进行安静活动直到困倦。'
    });
  }
  
  if (components.sleep_disturbances.score >= 2) {
    const mainDisturbances = components.sleep_disturbances.details.mainDisturbances;
    if (mainDisturbances.length > 0) {
      const factors = mainDisturbances.map(d => d.factor).join('、');
      recommendations.push({
        type: 'suggestion',
        title: '减少睡眠干扰',
        content: `主要干扰因素包括：${factors}。建议针对性地解决这些问题，如调节室温、使用耳塞等。`
      });
    }
  }
  
  if (components.sleep_medication.score >= 1) {
    recommendations.push({
      type: 'warning',
      title: '关于睡眠药物使用',
      content: '长期使用睡眠药物可能产生依赖性。建议在医生指导下使用，并尝试非药物改善睡眠的方法。'
    });
  }
  
  if (components.daytime_dysfunction.score >= 2) {
    recommendations.push({
      type: 'suggestion',
      title: '改善日间功能',
      content: '保持规律的作息时间，适当进行日间运动，避免长时间午睡。如持续困倦，建议咨询医生。'
    });
  }
  
  // 基于睡眠伙伴观察的建议
  const partnerInfo = getSleepPartnerInfo(formData);
  if (partnerInfo.hasPartner && partnerInfo.observations.length > 0) {
    const behaviors = partnerInfo.observations.map(o => o.behavior).join('、');
    recommendations.push({
      type: 'medical',
      title: '睡眠行为异常',
      content: `睡眠伙伴观察到：${behaviors}。这些可能是睡眠障碍的表现，建议咨询睡眠专科医生。`
    });
  }
  
  // 总体建议
  if (totalScore > 10) {
    recommendations.push({
      type: 'medical',
      title: '建议专业咨询',
      content: '您的睡眠问题较为严重，建议咨询睡眠专科医生或心理健康专家，进行进一步评估和治疗。'
    });
  }
  
  return recommendations;
}

/**
 * 生成PSQI评估报告
 * @param {Object} assessmentResult - 评估结果
 * @param {Object} formData - 表单数据
 * @returns {Object} 评估报告
 */
export function generatePSQIReport(assessmentResult, formData) {
  const { totalScore, components, qualityInfo, sleepPartnerInfo, recommendations } = assessmentResult;
  
  return {
    basicInfo: {
      name: formData.name || '未填写',
      age: formData.age || '未填写',
      gender: formData.gender === 'male' ? '男' : formData.gender === 'female' ? '女' : '未填写',
      assessmentDate: formData.assessment_date || new Date().toISOString().split('T')[0]
    },
    
    summary: {
      totalScore,
      maxScore: 21,
      qualityLevel: qualityInfo.label,
      description: qualityInfo.description
    },
    
    componentScores: Object.entries(components).map(([, component]) => ({
      name: component.name,
      score: component.score,
      maxScore: component.maxScore,
      percentage: ((component.score / component.maxScore) * 100).toFixed(1),
      details: component.details
    })),
    
    sleepHabits: {
      bedtime: formData.SL01 || '未填写',
      sleepLatency: (formData.SL02 || '未填写') + (formData.SL02 ? '分钟' : ''),
      wakeTime: formData.SL03 || '未填写',
      sleepDuration: (formData.SL04 || '未填写') + (formData.SL04 ? '小时' : ''),
      sleepEfficiency: components.sleep_efficiency.details.efficiency
    },
    
    sleepPartnerInfo,
    recommendations,
    
    generateTime: new Date().toLocaleString('zh-CN'),
    
    interpretation: {
      scoreRange: '0-21分',
      cutoffPoint: '5分',
      interpretation: totalScore <= 5 ? 
        '得分≤5分，表示睡眠质量良好' : 
        '得分>5分，表示睡眠质量较差，可能存在睡眠障碍'
    }
  };
}

/**
 * 验证PSQI表单数据
 * @param {Object} formData - 表单数据
 * @returns {Object} 验证结果
 */
export function validatePSQIForm(formData) {
  const errors = [];
  const warnings = [];
  
  // 个人信息字段已改为选填，不再进行必填验证
  // 只验证如果填写了年龄，则必须在有效范围内
  if (formData.age !== null && formData.age !== undefined && formData.age !== '') {
    const age = parseInt(formData.age);
    if (isNaN(age) || age < 1 || age > 120) {
      errors.push('年龄应在1-120岁之间');
    }
  }
  
  // 必填字段验证（不包括个人信息字段）
  const requiredFields = {
    assessment_date: '评估日期',
    SL01: '上床时间',
    SL02: '入睡时间',
    SL03: '起床时间',
    SL04: '睡眠时间',
    SL051: '入睡困难程度',
    SL052: '夜间易醒程度',
    SL053: '起床上洗手间频率',
    SL054: '呼吸不畅频率',
    SL055: '鼾声或咳嗽频率',
    SL056: '感到太冷频率',
    SL057: '感到太热频率',
    SL058: '做恶梦频率',
    SL059: '疼痛不适频率',
    SL06: '主观睡眠质量',
    SL07: '睡眠药物使用频率',
    SL08: '日间困倦频率',
    SL09: '精力不足频率',
    SL10: '睡眠伙伴情况'
  };
  
  Object.entries(requiredFields).forEach(([field, label]) => {
    if (!formData[field] && formData[field] !== 0) {
      errors.push(`${label}为必填项`);
    }
  });
  
  // 数据合理性验证（年龄验证已在上面处理）
  
  if (formData.SL02 && (formData.SL02 < 0 || formData.SL02 > 300)) {
    errors.push('入睡时间应在0-300分钟之间');
  }
  
  if (formData.SL04 && (formData.SL04 < 0 || formData.SL04 > 24)) {
    errors.push('睡眠时间应在0-24小时之间');
  }
  
  // 条件性字段验证
  const partnerStatus = parseInt(formData.SL10);
  if (partnerStatus > 1) {
    const partnerQuestions = ['SL101', 'SL102', 'SL103', 'SL104'];
    const partnerLabels = ['高声打鼾', '呼吸暂停', '腿部抽动', '意识模糊'];
    
    partnerQuestions.forEach((field, index) => {
      if (formData[field] === undefined || formData[field] === null) {
        warnings.push(`建议填写睡眠伙伴观察到的${partnerLabels[index]}情况`);
      }
    });
  }
  
  // 逻辑一致性检查
  if (formData.SL01 && formData.SL03 && formData.SL04) {
    const bedtime = formData.SL01;
    const wakeTime = formData.SL03;
    const sleepDuration = parseFloat(formData.SL04);
    
    const bedtimeHour = parseInt(bedtime.split(':')[0]);
    const waketimeHour = parseInt(wakeTime.split(':')[0]);
    
    let timeInBed = waketimeHour - bedtimeHour;
    if (timeInBed <= 0) timeInBed += 24;
    
    if (sleepDuration > timeInBed + 1) {
      warnings.push('实际睡眠时间似乎超过了在床时间，请检查填写是否正确');
    }
  }
  
  return {
    isValid: errors.length === 0,
    errors,
    warnings,
    hasWarnings: warnings.length > 0
  };
}

export default {
  calculatePSQIAssessment,
  generatePSQIReport,
  validatePSQIForm
};